'use strict';

const Service = require('egg').Service;

class UserService extends Service {
  // 根据用户名或邮箱查找用户
  async findByUsernameOrEmail(username, email) {
    const { Op } = this.app.Sequelize;
    
    return await this.ctx.model.User.findOne({
      where: {
        [Op.or]: [
          { username },
          { email },
        ],
      },
    });
  }

  // 根据ID查找用户
  async findById(id) {
    return await this.ctx.model.User.findByPk(id, {
      attributes: { exclude: ['password'] },
    });
  }

  // 创建用户
  async create(userData) {
    return await this.ctx.model.User.create(userData);
  }

  // 根据ID更新用户
  async updateById(id, updateData) {
    return await this.ctx.model.User.update(updateData, {
      where: { id },
    });
  }

  // 更新最后登录时间
  async updateLastLogin(id) {
    return await this.ctx.model.User.update(
      { last_login_at: new Date() },
      { where: { id } }
    );
  }

  // 生成JWT token
  async generateToken(user) {
    const payload = {
      id: user.id,
      username: user.username,
      email: user.email,
    };
    
    return this.app.jwt.sign(payload, this.app.config.jwt.secret, {
      expiresIn: this.app.config.jwt.expiresIn,
    });
  }

  // 验证JWT token
  async verifyToken(token) {
    try {
      return this.app.jwt.verify(token, this.app.config.jwt.secret);
    } catch (error) {
      return null;
    }
  }

  // 获取用户统计信息
  async getStats(userId) {
    const clothingCount = await this.ctx.model.Clothing.count({
      where: { user_id: userId },
    });

    const outfitCount = await this.ctx.model.Outfit.count({
      where: { user_id: userId },
    });

    const wearRecordCount = await this.ctx.model.WearRecord.count({
      where: { user_id: userId },
    });

    const favoriteClothingCount = await this.ctx.model.Clothing.count({
      where: { 
        user_id: userId,
        is_favorite: true,
      },
    });

    const favoriteOutfitCount = await this.ctx.model.Outfit.count({
      where: { 
        user_id: userId,
        is_favorite: true,
      },
    });

    return {
      clothing_count: clothingCount,
      outfit_count: outfitCount,
      wear_record_count: wearRecordCount,
      favorite_clothing_count: favoriteClothingCount,
      favorite_outfit_count: favoriteOutfitCount,
    };
  }

  // 获取用户偏好
  async getPreferences(userId) {
    return await this.ctx.model.UserPreference.findAll({
      where: { user_id: userId },
      order: [['preference_type', 'ASC'], ['weight', 'DESC']],
    });
  }

  // 设置用户偏好
  async setPreference(userId, preferenceType, preferenceKey, preferenceValue, weight = 1) {
    const existingPreference = await this.ctx.model.UserPreference.findOne({
      where: {
        user_id: userId,
        preference_type: preferenceType,
        preference_key: preferenceKey,
      },
    });

    if (existingPreference) {
      return await this.ctx.model.UserPreference.update(
        { 
          preference_value: preferenceValue,
          weight,
        },
        {
          where: {
            user_id: userId,
            preference_type: preferenceType,
            preference_key: preferenceKey,
          },
        }
      );
    } else {
      return await this.ctx.model.UserPreference.create({
        user_id: userId,
        preference_type: preferenceType,
        preference_key: preferenceKey,
        preference_value: preferenceValue,
        weight,
      });
    }
  }

  // 删除用户偏好
  async removePreference(userId, preferenceType, preferenceKey) {
    return await this.ctx.model.UserPreference.destroy({
      where: {
        user_id: userId,
        preference_type: preferenceType,
        preference_key: preferenceKey,
      },
    });
  }
}

module.exports = UserService;
